package com.ruoyi.web.controller.system;


import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.MobileLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.MTeacherMapper;
import com.ruoyi.system.mapper.SysTeacherUserMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserStudentMapper;
import com.ruoyi.system.service.IStudentService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysTeacherUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Set;

/**
 * 登录控制器
 *
 * @author SK
 * @since 2018/6/13
 */
@RestController
@SessionAttributes("user")
@Transactional(rollbackFor = Exception.class)
@RequestMapping("/mobile/user")
public class UserController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysUserStudentMapper userStudentMapper;

    @Autowired
    private IStudentService iStudentService;

    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private MobileLoginService loginService;
    @Autowired
    private MTeacherMapper mTeacherMapper;

    @Autowired
    private SysTeacherUserServiceImpl sysTeacherUserService;

    /**
     * 注册用户
     *
     * @return -1 用户名或密码错误  -2 账号冻结  -3 账号锁定 1 成功  -4 验证码错误
     */
    @PostMapping("/registerUser")
    @ResponseBody
    public AjaxResult registerUser(HttpServletRequest request) {

        String phoneNo = request.getParameter("phoneNo");
        String validCode = request.getParameter("validCode");
        String password = request.getParameter("password");
        String current = request.getParameter("current");
        String cid = request.getParameter("cid");



        // 登录结果
        LoginParams loginParams = new LoginParams();
        loginParams.setPhoneNo(phoneNo);
        loginParams.setValidCode(validCode);
        loginParams.setPassword(password);
        loginParams.setValidCodeType(current);
        loginParams.setCid(cid);
        return loginService.registerUser(loginParams);
    }

    /**
     * 修改密码
     * @return -1 用户名或密码错误  -2 账号冻结  -3 账号锁定 1 成功  -4 验证码错误
     */
    @PostMapping("/forget")
    @ResponseBody
    public AjaxResult forget(HttpServletRequest request) {

        String phoneNo = request.getParameter("phoneNo");
        String password = request.getParameter("password");
        String validCode = request.getParameter("validCode");


        // 登录结果
        LoginParams loginParams = new LoginParams();
        loginParams.setPhoneNo(phoneNo);
        loginParams.setPassword(password);
        loginParams.setValidCode(validCode);
        return loginService.forget(loginParams);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getUserInfo")

    public AjaxResult getUserInfo(HttpServletRequest request) {
        SysUser user = SecurityUtils.getLoginUser().getUser();

        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
//        return ajax;
//        LoginUser loginUser = tokenService.getLoginUser(request);
//        SysUser user = sysUserService.selectUserById(loginUser.getUser().getUserId());
//        AjaxResult ajax = AjaxResult.success();
//        ajax.put("user", user);
        return ajax;
    }


    /**
     * 注册普通用户
     *
     * @return 用户信息
     */
    @PostMapping("registerUserInfo")
    @ResponseBody
    @Transactional(rollbackFor = {Exception.class})
    public AjaxResult registerUserInfo(@RequestBody RegisterUserItem registerUserItem) {

        List<Student> studentArray = null;
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();


            //修改用户
            SysUser user = loginUser.getUser();
            user.setNickName(registerUserItem.getNickName());
            user.setPhonenumber(registerUserItem.getPhonenumber());
            user.setSex(registerUserItem.getSex());
            user.setEmail(registerUserItem.getAddress());
            userMapper.updateUser(user);


            //联系人
            List<ScStudentContact> contactArray = registerUserItem.getContactArray();
            ScStudentContact scStudentContact = new ScStudentContact();
            scStudentContact.setContactNick(registerUserItem.getNickName());
            scStudentContact.setContactPhone(registerUserItem.getPhonenumber());
            scStudentContact.setContactRelation(registerUserItem.getRelation());
            contactArray.add(scStudentContact);

            //学生与用户
            studentArray = registerUserItem.getStudentArray();
            for (Student student : studentArray
            ) {
                student.setContactList(contactArray);
                iStudentService.insertStudent(student);
                SysUserStudent sysUserStudent = new SysUserStudent();
                sysUserStudent.setStudentId(student.getId());
                sysUserStudent.setUserId(user.getUserId());
                userStudentMapper.insertSysUserStudent(sysUserStudent);
            }

        } catch (Exception e) {
            AjaxResult.error("注册失败");
        }


        return AjaxResult.success(studentArray);
    }

    /**
     * 注册教师用户
     *
     * @return 用户信息
     */
    @PostMapping("registerTeacherInfo")
    @ResponseBody
    @Transactional(rollbackFor = {Exception.class})
    public AjaxResult registerTeacherInfo(@RequestBody RegisterUserItem registerUserItem) {
        SysUser user =new SysUser();
        MTeacher mTeacher = new MTeacher();
        try {


            user.setNickName(registerUserItem.getNickName());
            user.setPhonenumber(registerUserItem.getPhonenumber());
            user.setSex(registerUserItem.getSex());
            user.setEmail(registerUserItem.getAddress());
            user.setUserName(registerUserItem.getPhonenumber());
            user.setDeptId(103L);
            userMapper.updatePhonenumberUser(user);




            mTeacher.setName(registerUserItem.getNickName());
            mTeacher.setSex(registerUserItem.getSex());
            mTeacher.setCourse(registerUserItem.getCourse());
            mTeacher.setNumber(registerUserItem.getPhonenumber());
            mTeacherMapper.insertMTeacher(mTeacher);

            SysTeacherUser sysTeacherUser = new SysTeacherUser();
            sysTeacherUser.setTeacherId(mTeacher.getId());
            sysTeacherUser.setUserId(user.getUserId());




            int i = sysTeacherUserService.insertSysTeacherUser(sysTeacherUser);










        } catch (Exception e) {
            AjaxResult.error("注册失败");
        }


        return AjaxResult.success(mTeacher.getId());
    }


    @PostMapping({"saveUserInfo"})
    @ResponseBody
    public AjaxResult saveUserInfo(SysUser user, HttpServletRequest request) {
        AjaxResult ajax = AjaxResult.success("个人信息修改成功！");
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        currentUser = sysUserService.selectUserById(currentUser.getUserId());
        if (StringUtils.isNotBlank(user.getNickName())) {
            currentUser.setNickName(user.getNickName());
        }
        if (StringUtils.isNotBlank(user.getEmail())) {
            currentUser.setEmail(user.getEmail());
        } else {
            currentUser.setEmail("");
        }
        if (StringUtils.isNotBlank(user.getPhonenumber())) {
            currentUser.setPhonenumber(user.getPhonenumber());
        } else {
            currentUser.setPhonenumber("");
        }
        if (StringUtils.isNotBlank(user.getSex())) {
            currentUser.setSex(user.getSex());
        }
        sysUserService.updateUser(currentUser);
        return ajax;
    }
}
